package fatboy.addons;
/**
 * @author James
 * @domain 
 */
import java.util.List;

import junit.framework.Assert;
import fatboy.hypeerweb.Node;

/**
 * The Visitor Broadcast.
 * @domain domain of Listener
 */
public class Broadcast2 extends Broadcast implements Visitor{

	private Listener caller;
	/**
	 * Constructor that accepts the listener that this broadcast should notify when all nodes have
	 * reported
	 * @param caller the listener this node should be listening to
	 * @pre true
	 * @post returns a instance of this class that will report to the listener passed in
	 */
	
	public Broadcast2(Listener caller){
		this.caller = caller;
	}
	/**
	 * a constructor to make the remote proxy for this class work
	 */
	public Broadcast2(){
		caller = null;
	}
	/**
	 * this method will send a new instance of this class to all of the nodes in the tree(formed
	 * from broadcastOrigin) lower than it
	 * then this Node.
	 * @pre thisNode and broadcastOrigin are in the same hypeerweb
	 * @post all nodes lower than thisNode will have received the message and a listener will be
	 * waiting for them to report then will report afterwards
	 */
	public boolean broadcast(Node thisNode, Node broadcastOrigin){
		boolean acknowledgement = true;
		List<Node> broadcastList = getBroadcastList(thisNode, broadcastOrigin.getAddress());
		Listener counter = new Listener(broadcastList.size(),caller); 
		for (Node toBroadcast : broadcastList) {
		/*	System.out.println(thisNode.getAddress()+" sending broadcast to "
					+ toBroadcast.getAddress());*/		
			acknowledgement &= toBroadcast.accept(new Broadcast2(counter)
					, broadcastOrigin);
		}
		return acknowledgement;
	}
	@Override
	public void visit(Node thisNode, Object broadcastNode) {	
		Assert.assertTrue(broadcastNode instanceof Node);
		Node broadcastOrigin = (Node) broadcastNode;			
		broadcast(thisNode, broadcastOrigin);
	}
	public Object writeReplace(){
		return new ProxyBroadcast2(this.getId());
	}
}
